package com.zqw.controller;

import com.zqw.info.GoodsInfo;
import com.zqw.info.UserInfo;
import com.zqw.pojo.UserPojo;
import com.zqw.service.UserService;
import com.zqw.util.MD5Util;
import com.zqw.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class UserController {

    @Autowired
    UserService userService;

    @RequestMapping("jump")
    public String jump(HttpSession session){
        session.removeAttribute("user");
        session.removeAttribute("shopCt");
        return "login";
    }

    //登录
    @RequestMapping("login")
    @ResponseBody
    public String login(UserPojo user,HttpSession session){
        int i = 1;
        if(StringUtil.isEmpty(user.getCaccount())||StringUtil.isEmpty(user.getCpass())){
        }else {
            user.setCpass(MD5Util.getMd5(user.getCpass()));
            UserInfo login = userService.login(user);
            if(login!=null){
                List<GoodsInfo> shopCt = (List<GoodsInfo>) session.getAttribute("shopCt");
                List<GoodsInfo> goodsInfos = userService.updShopCar(shopCt, String.valueOf(login.getCid()));
                session.setAttribute("shopCt",goodsInfos);
                session.setAttribute("user",login);
                i=0;
            }
        }
        return "{\"msg\":\""+i+"\"}";
    }

    //用户名唯一校验
    @RequestMapping("soleNameing")
    @ResponseBody
    public String soleName(String caccount) {
        Boolean soleName = userService.soleName(caccount);
        if(soleName==null) {
            return "{\"msg\":\"000\"}";
        }else {
            return "{\"msg\":\"001\"}";
        }
    }

    //注册
    @RequestMapping("registting")
    public String regist(UserInfo user, HttpServletRequest req) {
        if(user.getCaccount().equals("")||user.getCpass().equals("")) {
            req.setAttribute("mss", "注册失败");
            return "error";
        }
        user.setCpass(MD5Util.getMd5(user.getCpass()));
        boolean regist = userService.regist(user);
        if(regist) {
            return "login";
        }
        return "error";
    }

}
